require 'yaml'
require "map_editor/model"
require 'dgo/tile_map/map_loader'
require "dgo/io/json_builder"

module MapEditor
  class IO
    include DGO::IO
    def self.load(map_id)
      return Model.new(map_id, DGO::TileMap::MapLoader.load_map($res.root_path, "data/map/#{map_id}.yaml", true))
    end

    def self.get_layer_data(model)
      chipsets = {}

      no = 0
      arr = []
      model.layers.each do |layer|
        str = ""
        layer.map_data.each_with_two_index do |tile, x, y|
          t = ""
          if tile.palet_chip.chipset
            unless chipsets[tile.palet_chip.chipset.type]
              chipsets[tile.palet_chip.chipset.type] = {}
            end
            unless chipsets[tile.palet_chip.chipset.type][tile.palet_chip.chipset.name]
              chipsets[tile.palet_chip.chipset.type][tile.palet_chip.chipset.name] = {:no => no}
              no += 1
            end
            if tile.palet_chip.chipset.nil?
              t = ""
            else
              t = "#{chipsets[tile.palet_chip.chipset.type][tile.palet_chip.chipset.name][:no]}-#{tile.palet_chip.no}"
            end
          end

          if x == model.tile_x_count - 1
            str += "#{t}\n"
          else
            str += "#{t},"
          end
        end
        arr << str
      end
      return arr, chipsets
    end
    
    def self.get_collision_data(model)
      str = ""
      model.map.collision_data.each_with_two_index do |collision, x, y|
        t = collision
        if x == model.tile_x_count - 1
          str += "#{t}\n"
        else
          str += "#{t},"
        end
      end
      return str
    end
    
    def self.get_chipsets_data(chipsets)
      arr = []
      i = 0
      while(!chipsets.empty?)
        chipsets.each do |key1, type|
          type.each do |key2, chipset|
            if chipset[:no] == i
              arr << {"type" => key1.to_s, "id" => key2}
              chipsets[key1].delete(key2)
              chipsets.delete(key1) if chipsets[key1].empty?
              i += 1
              break
            end
          end
        end
      end

      return arr
    end

    def self.save_map(model)
      data = {}

      data["editor"] = {}
      data["editor"]["chipsets"] = {"base" => model.base_chipset.name, "anime" => model.anime_chipset.name}
      data["x_count"] = model.tile_x_count
      data["y_count"] = model.tile_y_count
      data["gw"] = model.grid_width.floor
      data["gh"] = model.grid_height.floor

      data["layers"], chipsets = IO.get_layer_data(model)
      data["panorama"] = File.basename(model.panorama.texture_id) if model.panorama
      data["collision"] = IO.get_collision_data(model)
      data["chipsets"] = IO.get_chipsets_data(chipsets)
      
      yaml = data.to_yaml
      File.open("#{$res.data_path}map/#{model.map_id}.yaml", "w+") do |f|
        f.write(yaml)
      end
      
      #JSON Format
      File.open("#{$res.data_path}map/#{model.map_id}.json", "w+") do |f|
        f.write(JsonBuilder.new.build(data))
      end
    end
    
    def self.save_chipset(chipset, type)
      chipset_info = {"collision" => [], "priority" => []}
      chipset.palet_chips.each do |palet_chip|
        chipset_info["collision"] << palet_chip.collision_type
        chipset_info["priority"] << palet_chip.priority
      end

      yaml = chipset_info.to_yaml
      File.open("#{$res.data_path}chipsets/#{type}/#{chipset.name}.yaml", "w+") do |f|
        f.write(yaml)
      end
      
       #JSON Format
      File.open("#{$res.data_path}chipsets/#{type}/#{chipset.name}.json", "w+") do |f|
        f.write(JsonBuilder.new.build(chipset_info))
      end
    end
    
    def self.save_chipsets(model)
      IO.save_chipset(model.base_chipset, "base")
      IO.save_chipset(model.anime_chipset, "anime")
      
      chipset_info = {}
      model.auto_chipsets.each do |chipset|
        chipset.palet_chips.each do |palet_chip|
          chipset_info[palet_chip.chipset.name] = {"collision" => [palet_chip.collision_type], "priority" => [palet_chip.priority]}
        end
      end

      yaml = chipset_info.to_yaml
      File.open("#{$res.data_path}chipsets/auto/setting.yaml", "w+") do |f|
        f.write(yaml)
      end
      
      #JSON Format
      File.open("#{$res.data_path}chipsets/auto/setting.json", "w+") do |f|
        f.write(JsonBuilder.new.build(chipset_info))
      end
    end

    def self.save(model)
      IO.save_chipsets(model)
      IO.save_map(model)
    end
    
    def self.get_panorama_list
      arr = []
      arr << ["none", nil]
      Dir::glob("#{$res.image_path}game/panorama/*").each do |path|
        if File.file?(path)
          t = File.basename(path).split(".")[0]
          arr << [t, t]
        end
      end
      return arr
    end
    
    def self.get_base_chipset_list
      arr = []
      Dir::glob("#{$res.image_path}game/map/base/*").each do |path|
        if File.file?(path)
          t = File.basename(path).split(".")[0]
          arr << [t, t]
        end
      end
      return arr
    end

    def self.get_anime_chipset_list
      arr = []
      Dir::glob("#{$res.image_path}game/map/anime/*_1.png").each do |path|
        if File.file?(path)
          t = File.basename(path).sub("_1.png", "")
          arr << [t, t]
        end
      end
      return arr
    end
  end
end